package mi.payment.transaction.authorize.base;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import lainey.ui.utils.LogUtil;
import lainey.ui.widget.TitleView;
import mi.payment.CardType;
import mi.payment.R;
import mi.payment.constants.Configs;
import mi.payment.db.dao.PayDetail;
import mi.payment.settings.TransactionOtherOperation;
import mi.payment.transaction.V2BaseSwingCardActivity;

/**
 * 刷卡和手输卡号界面
 *
 * @author lj on 2017/3/5.
 */
public class PreAuthorizeInputInfoSwingActivity extends V2BaseSwingCardActivity {

    private View mClearView;

    public TextView mTvTitle;
    public EditText mEditCardNumber;
    public EditText mEditYear;
    public EditText mEditMonth;

    private boolean isCheckedCard;

    public void onClickOK() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.authorize_activity_swing_and_input_card);
        initView();
        startCheckCard();
    }

    private void initView() {
        TitleView titleView = findViewById(R.id.title_view);
        mTvTitle = titleView.getCenterTextView();
        titleView.setLeftImageOnClickListener(
                v -> onBackPressed()
        );

        mEditCardNumber = findViewById(R.id.edit_card_num);
        mEditMonth = findViewById(R.id.edit_month);
        mEditYear = findViewById(R.id.edit_year);
        mClearView = findViewById(R.id.iv_clear);

        mClearView.setVisibility(View.GONE);

        // 点击确认
        findViewById(R.id.mb_ok).setOnClickListener(
                v -> {
                    // 校验卡号
                    String str = mEditCardNumber.getText().toString();
                    String cardNo = getDeleteSpaceCardNumber(str);
                    if (cardNo.length() < 13 || cardNo.length() > 19) {
                        showToast(R.string.error_input_card_number_hint);
                        return;
                    }
                    // 校验卡有效期
                    String year = mEditYear.getText().toString();
                    String month = mEditMonth.getText().toString();
                    boolean valid = (year.length() != 0 || month.length() != 0) && (year.length() != 2 || month.length() != 2);
                    if (valid) {
                        showToast(R.string.error_exp_date);
                        return;
                    }

                    PayDetail payDetail = mTradeData.getPayDetail();
                    if (isCheckedCard) { // 是否为手工输入卡号
                        LogUtil.e(Configs.TAG, "开始检卡");
                    } else {
                        abortCheckCard();
                        payDetail.cardType = CardType.NO_CARD.getValue();
                    }
                    payDetail.setCardNo(cardNo);
                    if (year.length() == 2) {
                        payDetail.setEXPDate(year + month);
                    }

                    onClickOK();
                }
        );

        mClearView.setOnClickListener(
                v -> mEditCardNumber.setText("")
        );
        mEditCardNumber.addTextChangedListener(mCardNumberTextWatcher);

        TextView tvHint = findViewById(R.id.tv_hint);
        // 是否可以手动输入卡号
        boolean isInputCardNum = TransactionOtherOperation.getInstance().getTransactionOtherSettings().getInputCardNum();
        if (isInputCardNum) {
            String temp = getString(R.string.swing_card_hint) + ", " + getString(R.string.swing_card_input_hint);
            tvHint.setText(temp);
            mEditCardNumber.setEnabled(true);
            mEditMonth.setEnabled(true);
            mEditYear.setEnabled(true);
        } else {
            mEditCardNumber.setEnabled(false);
            mEditMonth.setEnabled(false);
            mEditYear.setEnabled(false);
            tvHint.setText(R.string.swing_card_hint);
        }

        setAmount(1);
    }

    @Override
    public void onCheckCardSuccess() {
        isCheckedCard = true;
        PayDetail payDetail = mTradeData.getPayDetail();
        if (payDetail.CardNo != null && payDetail.CardNo.length() > 0) {
            mEditCardNumber.setText(payDetail.CardNo);
            mEditCardNumber.setFocusable(false);
            mClearView.setVisibility(View.GONE);
        }
        if (payDetail.EXPDate != null && payDetail.EXPDate.length() > 0) {
            String year = payDetail.getEXPDate().substring(0, 2);
            String month = payDetail.getEXPDate().substring(2, 4);
            mEditYear.setText(year);
            mEditMonth.setText(month);
            mEditMonth.setFocusable(false);
            mEditYear.setFocusable(false);
        }
    }

    private TextWatcher mCardNumberTextWatcher = new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            onNumberChanged(s);
            boolean inputCardNum = TransactionOtherOperation.getInstance().getTransactionOtherSettings().getInputCardNum();
            if (inputCardNum) {
                if (s.length() > 0) {
                    mClearView.setVisibility(View.VISIBLE);
                } else {
                    mClearView.setVisibility(View.GONE);
                }
            } else {
                mClearView.setVisibility(View.GONE);
            }
        }

    };

    private void onNumberChanged(Editable s) {
        String str = s.toString().trim().replace(" ", "");
        String result = "";
        if (str.length() > 19) {
            str = str.substring(0, 19);
        }
        if (str.length() >= 4 && str.length() <= 19) {
            mEditCardNumber.removeTextChangedListener(mCardNumberTextWatcher);
            for (int i = 0; i < str.length(); i++) {
                result += str.charAt(i);
                boolean flag = (i + 1) % 4 == 0;
                if (flag) {
                    result += " ";
                }
            }
            boolean b = result.endsWith(" ");
            if (b) {
                result = result.substring(0, result.length() - 1);
            }
            mEditCardNumber.setText(result);
            mEditCardNumber.addTextChangedListener(mCardNumberTextWatcher);
            int length = mEditCardNumber.getText().toString().length();
            mEditCardNumber.setSelection(length); // 焦点到输入框最后位置
        }
    }

    public String getDeleteSpaceCardNumber(String number) {
        if (number != null) {
            number = number.replace(" ", "");
        }
        return number;
    }


}
